package main

import (
	//"fmt"
	"bytes"

	"git.oschina.net/yangdao/SGNet2"
	"git.oschina.net/yangdao/SGNet2/Server"
	"git.oschina.net/yangdao/extlib/log"
)

type ChatServer struct {
	Server.Server
}

func NewChatServer() *ChatServer {
	chatServer := &ChatServer{
		Server: *Server.NewServer(),
	}
	chatServer.Server.UpdateFunc = chatServer.Update
	chatServer.AddNetHandler()
	return chatServer
}

func (this *ChatServer) AddNetHandler() {
	this.Server.MessageHandlerDic[0] = this.OnLoginHanler
	this.Server.MessageHandlerDic[999] = this.OnLoginOutHandler
}

func (this *ChatServer) Run() {
	this.Server.Run()
}

func (this *ChatServer) Update() {

}

func (this *ChatServer) OnLoginHanler(msg *Server.Messge) {
	log.Log("ChatSever", "用户登录成功", string(msg.Data))

	msg.Sess.Send(1, bytes.NewBufferString("登录成功").Bytes())
}

func (this *ChatServer) OnLoginOutHandler(msg *Server.Messge) {
	log.Log("ChatSever", "用户登出成功", msg.Sess.ID)
}

func (this *ChatServer) OnSessionStateMessge(msg *SGNet2.Session, msgType int) {
	switch msgType {
	case SGNet2.SGNetMsg_SessionLost:
		lostMessage := Server.Messge{ID: 999, Sess: msg}
		log.Log("ChatServer,Info", "ChatServer收到一个Session断开的消息", msg.ID)
		chatServer.PushMessage(&lostMessage)
	case SGNet2.SGNetMsg_SessionNew:
		log.Log("ChatServer,Info", "ChatServer收到新的Session", msg.ID)
		msg.DataReceiveEvent.Conj(this.OnSeesionPackage)
	}
}
func (this *ChatServer) OnSeesionPackage(sess *SGNet2.Session, msgId uint16, data []byte) {
	this.Server.PushMessage(&Server.Messge{
		ID:   msgId,
		Data: data,
		Sess: sess,
	})
}
